package com.ziyueyuwen.xiniao.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ziyueyuwen.xiniao.base.exception.nullpoint.LessonNotExistException;
import com.ziyueyuwen.xiniao.base.exception.nullpoint.UserNotExistException;
import com.ziyueyuwen.xiniao.bean.*;
import com.ziyueyuwen.xiniao.bean.vo.ZyClassLessonUserVO;
import com.ziyueyuwen.xiniao.bean.vo.ZyClassVO;
import com.ziyueyuwen.xiniao.dao.ZyClassLessonTransferMapper;
import com.ziyueyuwen.xiniao.service.ClassService;
import com.ziyueyuwen.xiniao.service.LessonUserService;
import com.ziyueyuwen.xiniao.service.TransferStudentService;
import com.ziyueyuwen.xiniao.service.UserService;
import com.ziyueyuwen.xiniao.service.baseservice.lesson.ZyClassLessonService;
import com.ziyueyuwen.xiniao.util.EEOUtil;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static com.ziyueyuwen.xiniao.util.ConstUtil.KEY_ERRNO;
import static com.ziyueyuwen.xiniao.util.ConstUtil.KEY_SYNC_RESULT;

/**
 * @author wancheng  on 2019/3/6.
 */
@Service
public class TransferStudentServiceImpl implements TransferStudentService {

    @Autowired
    ZyClassLessonTransferMapper transferMapper;
    @Autowired
    ZyClassLessonService zyClassLessonService;
    @Autowired
    UserService userService;
    @Autowired
    ClassService classService;
    @Autowired
    LessonUserService lessonUserService;

    @Override
    public ZyClassLessonTransfer getTransferStudent(Integer lessonId, String userAccount) {
        ZyClassLessonTransfer param = new ZyClassLessonTransfer();
        param.setTransferLessonId(lessonId);
        param.setUserAccount(userAccount);
        return transferMapper.selectOne(param);
    }

    @Override
    public ZyClassLessonTransfer getTransferStudent(Integer classId, Integer lessonIndex) {
        ZyClassLessonTransfer param = new ZyClassLessonTransfer();
        param.setClassId(classId);
        param.setLessonIndex(lessonIndex);
        return transferMapper.selectOne(param);
    }

    @Override
    public List<ZyClassLessonUserVO> getTransferStudents(Integer classId, Integer lessonIndex) {
        ZyClassLessonTransfer param = new ZyClassLessonTransfer();
        param.setClassId(classId);
        param.setLessonIndex(lessonIndex);
        List<ZyClassLessonTransfer> transfers = transferMapper.select(param);
        if (transfers == null){
            return null;
        }
        List<ZyClassLessonUserVO> lessonUserVOs = new ArrayList<>();
        transfers.forEach(
                t->{
                    ZyClassLessonUserVO zyClassLessonUserVO = new ZyClassLessonUserVO();
                    ZyUser user = userService.getByAccount(t.getUserAccount());
                    zyClassLessonUserVO.setUserAccount(t.getUserAccount());
                    zyClassLessonUserVO.setUserName(user.getUserName());
                }
        );
        return lessonUserVOs;
    }

    @Override
    public List<ZyClassLessonTransfer> getTransferStudent(Integer lessonId) {
        ZyClassLessonTransfer param = new ZyClassLessonTransfer();
        param.setTransferLessonId(lessonId);
        return transferMapper.select(param);
    }

    @Override
    public void deleteTransferStudent(Integer lessonId, String userAccount) {
        ZyClassLessonTransfer param = new ZyClassLessonTransfer();
        param.setTransferLessonId(lessonId);
        param.setUserAccount(userAccount);
        transferMapper.delete(param);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteTransferStudent(Integer lessonId) {
        ZyClassLessonTransfer param = new ZyClassLessonTransfer();
        param.setTransferLessonId(lessonId);
        transferMapper.delete(param);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public JSONArray addTransferStudent(Integer lessonId, List<String> userAccounts) throws Exception {
        ZyClassLessonInfo lessonInfo = zyClassLessonService.getByPreKey(lessonId);
        ZyClassVO classInfo = classService.getClassInfoByClassId(lessonInfo.getClassId());
        if (lessonId == null) {
            throw new LessonNotExistException();
        }
        if (CollectionUtils.isEmpty(userAccounts)) {
            return null;
        }
        Date currentDate = new Date();
        List<ZyClassLessonTransfer> transfers = new ArrayList<>();
        JSONArray studentJson = new JSONArray();
        for (String userAccount : userAccounts) {
            ZyUser user = userService.getByAccount(userAccount);
            if (user == null) {
                throw new UserNotExistException(userAccount);
            }
            JSONObject student = new JSONObject();
            student.put("account", userAccount);
            student.put("name", user.getUserName());
            studentJson.add(student);
            ZyClassInfo originalClassInfo = classService.getStudentRecentlyClass(classInfo.getCourseId(), userAccount);
            ZyClassLessonTransfer transfer = new ZyClassLessonTransfer();
            transfer.setTransferLessonId(lessonId);
            transfer.setLessonIndex(lessonInfo.getLessonIndex());
            transfer.setUserAccount(userAccount);
            transfer.setCreateTime(currentDate);
            if (originalClassInfo != null) {
                transfer.setClassId(originalClassInfo.getId());
                //删除原先的课节记录
                ZyClassLessonInfo originalLesson = zyClassLessonService.getLesson(originalClassInfo.getId(), lessonInfo.getLessonIndex());
                if (originalClassInfo != null){
                    lessonUserService.deleteLessonStudent(originalLesson.getId(), userAccount);
                }
            }
            transfer.setCourseId(classInfo.getCourseId());
            transfers.add(transfer);
        }
        //同步eeo
        JSONArray res = null;
        if (CollectionUtils.isNotEmpty(studentJson)) {
            res = EEOUtil.addClassStudentMultiple(lessonInfo.getEeoCourseId(), lessonInfo.getEeoLessonId(), studentJson);
        }
        Map<String, ZyClassLessonTransfer> accountMap = transfers.stream().collect(Collectors.toMap(ZyClassLessonTransfer::getUserAccount, u -> u));
        List<ZyClassLessonTransfer> syncSuccess = new ArrayList<>();
        List<ZyClassLessonTransfer> syncError = new ArrayList<>();
        for (int i = 0; i < res.size(); i++) {
            JSONObject current = res.getJSONObject(i);
            if (current.getBoolean(KEY_SYNC_RESULT)) {
                syncSuccess.add(accountMap.get(current.getString("account")));
            } else {
                syncError.add(accountMap.get(current.getString("account")));
            }
        }
        if (CollectionUtils.isNotEmpty(syncSuccess)) {
            transferMapper.insertList(syncSuccess);
        }
        return res;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public JSONArray deleteTransferStudent(Integer lessonId, List<String> userAccounts) throws Exception {
        ZyClassLessonInfo lessonInfo = zyClassLessonService.getByPreKey(lessonId);
        if (lessonId == null) {
            throw new LessonNotExistException();
        }
        if (CollectionUtils.isEmpty(userAccounts)) {
            return null;
        }
        //eeo删除结果
        JSONArray res = null;
        if (CollectionUtils.isNotEmpty(userAccounts)) {
            res = EEOUtil.deleteClassStudentMultiple(lessonInfo.getEeoCourseId(), lessonInfo.getEeoLessonId(), userAccounts);
        }
        JSONArray syncRes = new JSONArray();
        for (int i = 0; i < res.size(); i++) {
            ZyUser user = userService.getByAccount(userAccounts.get(i));
            JSONObject current = res.getJSONObject(i);
            JSONObject jsonObj = new JSONObject();
            jsonObj.put("account", user.getUserAccount());
            jsonObj.put("name", user.getUserName());
            if (current.getIntValue(KEY_ERRNO) == 1) {
                deleteTransferStudent(lessonId, userAccounts.get(i));
                jsonObj.put("sync", true);
            } else {
                jsonObj.put("sync", false);
            }
            syncRes.add(jsonObj);
        }
        return syncRes;
    }

}
